using UnityEngine;
using UnityEngine.UI;
using System.Collections;
using TMPro;
using SomniumSpace.Bridge;
using SomniumSpace.Bridge.Player;

namespace UFMTESTING1
{
    public class JoinBlackIntro : MonoBehaviour
    {
        [Header("Intro Settings")]
        [SerializeField] private string welcomeText = "Welcome to emeralds Hell!";
        [SerializeField] private float holdSeconds = 5f;
        [SerializeField] private float fadeOutSeconds = 1.5f;

        [Header("Overlay Look")]
        [SerializeField] private Color backgroundColor = Color.black;
        [SerializeField] private Color textColor = Color.white;
        [SerializeField] private float textSize = 80f;
        [SerializeField] private float overlayDistance = 0.3f;
        [SerializeField] private Vector2 overlaySize = new Vector2(4000f, 4000f);

        [Header("Startup")]
        [Tooltip("If true, the intro fires immediately on Start using Camera.main if SomniumBridge isn't ready.")]
        [SerializeField] private bool fireImmediatelyIfBridgeUnavailable = true;
        [Tooltip("Max seconds to wait for SomniumBridge local player before falling back to Camera.main.")]
        [SerializeField] private float bridgeWaitTimeout = 4f;

        private ISomniumPlayer _localPlayer;
        private bool _started;
        private GameObject _overlayRoot;
        private CanvasGroup _canvasGroup;

        private void Start()
        {
            Debug.Log("[JoinBlackIntro] Start - waiting for local player.");
            StartCoroutine(StartupWatch());
        }

        private void OnEnable()
        {
            var container = SomniumBridge.PlayersContainer;
            if (container != null)
                container.OnLocalPlayerAdded += OnLocalPlayerJoined;
        }

        private void OnDisable()
        {
            var container = SomniumBridge.PlayersContainer;
            if (container != null)
                container.OnLocalPlayerAdded -= OnLocalPlayerJoined;
        }

        private IEnumerator StartupWatch()
        {
            float elapsed = 0f;
            while (!_started && elapsed < bridgeWaitTimeout)
            {
                var existing = SomniumBridge.PlayersContainer?.LocalPlayer;
                if (existing != null)
                {
                    Debug.Log("[JoinBlackIntro] Found existing local player via poll.");
                    OnLocalPlayerJoined(existing);
                    yield break;
                }
                yield return new WaitForSeconds(0.25f);
                elapsed += 0.25f;
            }

            if (!_started && fireImmediatelyIfBridgeUnavailable)
            {
                Debug.LogWarning("[JoinBlackIntro] Bridge never delivered a local player - falling back to Camera.main.");
                _started = true;
                StartCoroutine(RunIntroWithFallback());
            }
        }

        private void OnLocalPlayerJoined(ISomniumPlayer player)
        {
            if (_started) return;
            _started = true;
            _localPlayer = player;
            Debug.Log("[JoinBlackIntro] OnLocalPlayerJoined fired - starting intro.");

            var container = SomniumBridge.PlayersContainer;
            if (container != null)
                container.OnLocalPlayerAdded -= OnLocalPlayerJoined;

            StartCoroutine(RunIntro());
        }

        private IEnumerator RunIntro()
        {
            float wait = 0f;
            while ((_localPlayer?.References?.Body?.Head == null) && wait < 10f)
            {
                yield return new WaitForSeconds(0.1f);
                wait += 0.1f;
            }

            Transform head = _localPlayer?.References?.Body?.Head;
            if (head == null)
            {
                Debug.LogWarning("[JoinBlackIntro] Head transform null after wait - falling back to Camera.main.");
                yield return StartCoroutine(RunIntroWithFallback());
                yield break;
            }

            Debug.Log("[JoinBlackIntro] Building overlay parented to player head.");
            BuildOverlay(head);
            yield return PlayOverlaySequence();
        }

        private IEnumerator RunIntroWithFallback()
        {
            float wait = 0f;
            while (Camera.main == null && wait < 5f)
            {
                yield return new WaitForSeconds(0.1f);
                wait += 0.1f;
            }

            if (Camera.main == null)
            {
                Debug.LogError("[JoinBlackIntro] Camera.main also null - cannot show overlay.");
                yield break;
            }

            Debug.Log("[JoinBlackIntro] Building overlay parented to Camera.main.");
            BuildOverlay(Camera.main.transform);
            yield return PlayOverlaySequence();
        }

        private IEnumerator PlayOverlaySequence()
        {
            yield return new WaitForSeconds(holdSeconds);

            float t = 0f;
            while (t < fadeOutSeconds)
            {
                t += Time.deltaTime;
                if (_canvasGroup != null)
                    _canvasGroup.alpha = Mathf.Clamp01(1f - (t / fadeOutSeconds));
                yield return null;
            }

            if (_overlayRoot != null)
                Destroy(_overlayRoot);

            Debug.Log("[JoinBlackIntro] Intro complete.");
        }

        private void BuildOverlay(Transform parent)
        {
            int uiLayer = LayerMask.NameToLayer("UI");

            _overlayRoot = new GameObject("JoinBlackIntro_Overlay");
            _overlayRoot.transform.SetParent(parent, false);
            _overlayRoot.transform.localPosition = new Vector3(0f, 0f, overlayDistance);
            _overlayRoot.transform.localRotation = Quaternion.identity;
            _overlayRoot.transform.localScale = new Vector3(0.001f, 0.001f, 0.001f);

            var canvas = _overlayRoot.AddComponent<Canvas>();
            canvas.renderMode = RenderMode.WorldSpace;
            canvas.sortingOrder = 32767;
            _overlayRoot.AddComponent<CanvasScaler>();
            _overlayRoot.AddComponent<GraphicRaycaster>();

            var canvasRect = _overlayRoot.GetComponent<RectTransform>();
            canvasRect.sizeDelta = overlaySize;

            _canvasGroup = _overlayRoot.AddComponent<CanvasGroup>();
            _canvasGroup.alpha = 1f;
            _canvasGroup.blocksRaycasts = false;
            _canvasGroup.interactable = false;

            var bg = new GameObject("Background", typeof(RectTransform), typeof(Image));
            bg.transform.SetParent(_overlayRoot.transform, false);
            var bgRect = bg.GetComponent<RectTransform>();
            bgRect.anchorMin = Vector2.zero;
            bgRect.anchorMax = Vector2.one;
            bgRect.offsetMin = Vector2.zero;
            bgRect.offsetMax = Vector2.zero;
            var bgImg = bg.GetComponent<Image>();
            bgImg.color = backgroundColor;
            bgImg.raycastTarget = false;

            var textGo = new GameObject("WelcomeText", typeof(RectTransform));
            textGo.transform.SetParent(_overlayRoot.transform, false);
            var textRect = textGo.GetComponent<RectTransform>();
            textRect.anchorMin = new Vector2(0.5f, 0.5f);
            textRect.anchorMax = new Vector2(0.5f, 0.5f);
            textRect.pivot = new Vector2(0.5f, 0.5f);
            textRect.anchoredPosition = Vector2.zero;
            textRect.sizeDelta = new Vector2(overlaySize.x * 0.9f, overlaySize.y * 0.5f);

            var tmp = textGo.AddComponent<TextMeshProUGUI>();
            tmp.text = welcomeText;
            tmp.color = textColor;
            tmp.fontSize = textSize;
            tmp.alignment = TextAlignmentOptions.Center;
            tmp.enableWordWrapping = true;
            tmp.raycastTarget = false;

            if (uiLayer >= 0)
                SetLayerRecursive(_overlayRoot, uiLayer);
        }

        private static void SetLayerRecursive(GameObject go, int layer)
        {
            go.layer = layer;
            foreach (Transform child in go.transform)
                SetLayerRecursive(child.gameObject, layer);
        }
    }
}
